<template>
	<view>
		<view>
			<view class="header" style="border-bottom: 1rpx solid lightgrey;">
				<view>
					<image style="background: #999999;height: 150rpx;width: 150rpx;border-radius: 100%;opacity: 0.7;"
						src="https://jkht.wteam.club/file/xiaochenxu/ZhiHuiWu.svg" mode="scaleToFill"
						v-if="domain =='https://shht.wteam.club/api' || domain =='https://admin3.51sioc.com/api'">
					</image>

					<image style="height: 150rpx;width: 150rpx;border-radius: 100%;"
						src="https://jkht.wteam.club/file/IndexIcon.jpg" mode="aspectFill"
						v-if="domain =='https://shht.wteam.club/app'"></image>


					<image style="height: 150rpx;width: 150rpx;border-radius: 100%;" src="/static/Index/taoMiaoMiao.png"
						mode="aspectFill" v-if="domain =='https://cw.tmmbuy.com/api'"></image>

					<image style="height: 150rpx;width: 150rpx;border-radius: 100%;"
						src="https://adminbg.czsgaf.com/file/wxfile/sangenUser.jpg" mode="aspectFill"
						v-if="domain =='https://userbg.czsgaf.com/api'"></image>



					<view class="tips" style="color: #000000;">云值守</view>
				</view>
			</view>
			<view>
				<view class="getItem">
					登录后云值守将获得以下权限
					<view class="item">• 获得你的公开信息（昵称、头像、地区
						等）</view>
				</view>
			</view>
			<!-- #ifdef MP-WEIXIN || H5 -->
			<!-- <button class="login" @click="OnSetUser">确认登录</button> -->
			<view v-if="showPrivacy" class="buttonIndex">
				<button class="login" @click="getPrivacy">确认登录</button>
			</view>

			<view @click="getUserInfo" v-else class="buttonIndex">
				<button class="login" open-type="getPhoneNumber" @getphonenumber="oneStep">确认登录</button>
			</view>
			<!-- #endif -->
			<!-- <button class="login" open-type="getPhoneNumber" @getphonenumber="oneStep">确认登录</button> -->

			<!-- #ifdef MP-ALIPAY -->
			<!-- <viewclass="buttonIndex">
			<button open-type="getAuthorize" onGetAuthorize="onGetAuthorize" onError="onAuthError" scope='phoneNumber' class="login">确认登录</button>
			</view> -->

			<!-- <view @click="getUserInfo" class="buttonIndex">
				<button class="login" open-type="getPhoneNumber" @getphonenumber="aliPayLogin">确认登录</button>
			</view> -->
			<view class="buttonIndex">
				<button class="login" open-type="getAuthorize" scope="phoneNumber" @getAuthorize="getPhoneNumber"
					onError="onAuthError">确认登录</button>
			</view>
			<!-- #endif -->
			<!-- 			<view @click="getuserinfo">
				<button class="login" open-type="getPhoneNumber" @getphonenumber="oneStep">确认登录</button>
			</view> -->
			<!-- <button class="login" open-type="getUserProfile" bindtap="getUserProfile">确认登录</button> -->
			<!-- <button class="login" @click="oneStep">确认登录</button> -->

		</view>
		<privacyPopup ref="privacyPopup" @confirm="confirm"></privacyPopup>
	</view>
</template>

<script>
	import privacyPopup from "@/components/privacyPopup/privacyPopup.vue";
	export default {

		data() {
			return {
				telephone: "", // 手机号码
				authCode: "", // 输入的验证码
				rightAuthCode: "", // 下发的验证码
				reGetTimeout: 0, // 重新获取验证码倒计时
				userInfo: null,
				OptionType: null,
				domain: "",
				storeid: '',
				code: "",
				showPrivacy: getApp().globalData.showPrivacy,
			}
		},
		components: {
			privacyPopup
		},
		onLoad(option) {
			this.domain = this.$api.Domain
			uni.setStorageSync("storeId", option.storeId)
			if (option) {

				if (option.type == 'ToVipCode') {
					this.OptionType = 'ToVipCode'
					this.storeid = option.storeid
				}
			}

			this.getWxCode()
		},
		methods: {
			onAuthError(err) {
				console.log('err', err);
				uni.showToast({
					title: '需要您授权手机号码后才能登录噢~',
					icon: 'none',
					duration: 2000
				})
			},
			// 支付宝手机号获取

			async getPhoneNumber() {
				let that = this;
				await this.aliPayLogin()
				await my.getPhoneNumber({
					success: (res) => {
						let encryptedData = res.response;
						console.log(res);
						console.log('99999999999');
						let data = {
							"data": encryptedData
						}
						my.request({
							//你的服务器地址
							url: this.$api.Domain + `/alipay/getPhone`,
							method:'post',
							header: {
								'content-type': 'application/json',
								'Authorization': that.$store.state.token,
								'token': that.$store.state.token
							},
							data:data
						});
					},
					fail: (res) => {
						console.log(res);
					},
				});
			},

			getWxCode() {
				// #ifdef MP-WEIXIN || H5 

				uni.login({
					success: (res1) => {
						console.log(2, res1);
						this.code = res1.code;
					}
				})
				// #endif

				// #ifdef MP-ALIPAY
				my.getAuthCode({
					scopes: 'auth_user',
					success: (auth) => {
						console.log('支付宝授权凭证', auth)

						this.code = auth.authCode;
					},
				});
				// #endif
			},
			confirm() {
				this.showPrivacy = false;
			},

			getPrivacy() {
				console.log(this.$refs.privacyPopup);
				this.$refs.privacyPopup.$refs.popup.open();
				if (getApp().globalData.showPrivacy) {
					this.$refs.privacyPopup.$refs.popup.open();
					return;
				}
			},

			async aliPayLogin() {

				let that = this;
				let data = {
					authCode: this.code
				}
				await uni.request({
					url: that.$api.AliLogin,
					data: data,
					method: 'GET',

					success(res4) {
						console.log('res4Code:', res4)
						if (res4.data.code == 200) {
							// 登录成功
							uni.hideLoading();

							uni.showToast({
								title: "登录成功",
								icon: 'success'
							});
							that.$store.state.avatarUrl =  res4
								.data.data.userInfo.avatarUrl;							
							uni.setStorageSync("token", res4
								.data.data.token);
							that.$store.state.token = res4.data.data
								.token;
							console.log('88888888888');
							setTimeout
								(() => {
										uni.redirectTo({
											url: "/pages/index/index"
										})
									},
									1000);
							// setTimeout
							// 	(() => {
							// 			if (that
							// 				.OptionType ==
							// 				'ToVipCode'
							// 			) {
							// 				uni.redirectTo({
							// 					url: "/pages/ToVipCode/ToVipCode?storeId=" +
							// 						that
							// 						.storeid
							// 				})
							// 			} else {
							// 				uni.redirectTo({
							// 					url: "/pages/index/index?type=login"
							// 				})
							// 			}
							// 		},
							// 		1000);
						} else {
							console.log(res4)
							uni.hideLoading();
							uni.showToast({
								title: "错误2",
								icon: 'error'
							});
							uni.clearStorage()
							this.getWxCode()
						}
					},
					fail(err) {
						return uni
							.showToast({
								icon: 'loading',
								title: '请求失败'
							});
						uni.hideLoading();
					}
				})

			},

			// 一键授权登录
			oneStep: function(e) {
				uni.showLoading({
					title: '加载中'
				});

				console.log(e)
				let ShouQuanCode = e.detail.code

				if (e.detail.errMsg == "getPhoneNumber:ok") {


					uni.getUserInfo({
						desc: '登录',
						success: (res) => {
							// 用户信息
							let userInfo = res.userInfo
							console.log(1, res);


							let data = {
								"signature": res.signature,
								"iv": res.iv,
								"encryptedData": res.encryptedData,
								"code": this.code,
							}

							this.$request(this.$api.login, data, "POST",
									false) //登录
								.then(res2 => {
									console.log(333, res2)

									if (res2.code == '200') {
										this.$store.state.avatarUrl = res2
											.data.userInfo.avatarUrl;											
										uni.setStorageSync("token", res2
											.data.token)
										this.$store.state.token = res2.data
											.token
										let data3 = {
											"avatarUrl": res2.data
												.userInfo
												.avatarUrl,
											"nickName": res2.data
												.userInfo
												.nickName,
											"userId": res2.data.userInfo
												.id,
										}
										// let data3 = {
										// 	"avatarUrl": this.userInfo
										// 		.avatarUrl,
										// 	"nickName": this.userInfo
										// 		.nickName,
										// 	"userId": res2.data.userInfo.id,
										// }
										let that = this

										uni.request({
											url: this.$api
												.perfectUserInfor,
											method: 'POST',
											data: data3,
											header: {
												Authorization: res2
													.data.token
											},
											success(res3) {

												console.log(res3
													.data,
													'res3Code')
												if (res3.data
													.code == 200) {
													console.log(
														'rescode3'
													)
													uni.setStorageSync(
														"user",
														JSON
														.stringify(
															res2
															.data
															.userInfo
														))

													// this.$store.state.user = JSON.stringify(res2.data.userInfo)

													let data2 = {
														"code": ShouQuanCode,
														"userId": res2
															.data
															.userInfo
															.id
													}
													console.log(
														'token333333',
														uni
														.getStorageSync(
															"token"
														))

													uni.request({
														url: that
															.$api
															.getPhone,
														data: data2,
														method: 'POST',
														header: {
															Authorization: res2
																.data
																.token
														},
														success(
															res4
														) {
															console
																.log(
																	'res4Code:',
																	res4
																)
															if (res4
																.data
																.code ==
																200
															) {
																// 登录成功
																uni
																	.hideLoading();


																uni.showToast({
																	title: "登录成功",
																	icon: 'success'
																});
																setTimeout
																	(
																		() => {
																			if (that
																				.OptionType ==
																				'ToVipCode'
																			) {
																				uni.redirectTo({
																					url: "/pages/ToVipCode/ToVipCode?storeId=" +
																						that
																						.storeid
																				})
																			} else {
																				uni.redirectTo({
																					url: "/pages/index/index?type=login"
																				})
																			}
																		},
																		1000
																	);
															} else {
																console
																	.log(
																		res4
																	)
																uni
																	.hideLoading();
																uni.showToast({
																	title: "错误2",
																	icon: 'error'
																});
																uni.clearStorage()
																this.getWxCode()
															}
														},
														fail(
															err
														) {
															return uni
																.showToast({
																	icon: 'loading',
																	title: '请求失败'
																})
														}
													})
												} else {
													uni
														.hideLoading();
													uni.showToast({
														title: "错误3",
														icon: 'error'
													});
													uni.clearStorage()
													this.getWxCode()
												}
											},
											fail: (err) => {
												return uni
													.showToast({
														icon: 'loading',
														title: '请求失败'
													})
											}
										})

									} else {
										uni.hideLoading()
										uni.showToast({
											title: "登录失败",
											icon: 'error'
										});
										uni.clearStorage()
										this.getWxCode()
									}
								})


						},
						fail: (res) => {
							uni.hideLoading()
							this.getWxCode()
							console.log(res)
						}
					});
				} else { // 拒绝授权
					uni.hideLoading()
					uni.showToast({
						title: '登录失败',
						icon: 'error'
					});
					this.getWxCode()
					uni.clearStorage()
					setTimeout(() => {
						uni.redirectTo({
							url: "/pages/index/index"
						})
					}, 2000)

				}


			},
			getUserInfo(e) {
				var _this = this;
				console.log(66, e)
				wx.getUserProfile({
					desc: '用于完善客户资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
					success: (res) => {
						console.log(res, '微信用户信息')
						if (!res.encryptedData || !res.iv) return false;
						this.userInfo = res.userInfo;
					},
					fail() {
						uni.showToast({
							title: '登录失败',
							icon: 'error'
						});
					}
				})
			},

			OnSetUser() {
				uni.login({
					success: (res1) => {
						let code = res1.code;
						console.log(2, res1);

						let url = "http://localhost:8091/admin/wxlogin"
						let data = {
							"avatar": "string",
							"code": res1.code,
							"nickName": "string"
						}
						this.$request(url, data, "POST", false).then(res4 => { //完善微信用户的电话号码
							console.log(444, res4)

							if (res4.code == 200) {

							} else {
								uni.hideLoading();
								uni.showToast({
									title: "错误",
									icon: 'error'
								});
							}
						})

					}
				})


			},
			testPay() {

				wx.requestPayment({
					"timeStamp": "1692939910",
					"nonceStr": "TGJIHRUBFXNWEXK0XYSGY5YRVIMHCUEZ",
					"package": "Sign=WXPay", // 
					"signType": "RSA",
					"paySign": "MDszMOEENoWqBRFCGnbtNrvPQ/cTmOgoSIGwsZp//qQawIHH9BgnToaDIk833RXt64CiTBF2/HNOd42vUADPs8CFDUAfLC/ZNHnfGGA870pcUig/hdUxfMeReqxc9mduyryUOY0nLXYizysRrzUjiar9besZ+WNIcy+7hA1/83E=",
					"success": (res) => {
						uni.showToast({
							title: "支付成功！",
							icon: 'success'
						});
						setTimeout(() => {
							let pages = getCurrentPages(); // 当前页面
							let beforePage = pages[pages.length - 2]; // 上一页
							uni.navigateBack({
								success: function() {
									beforePage.onLoad(); // 执行上一页的onLoad方法
								}
							});
						}, 1000);
					},
					"fail": (res) => {
						uni.showToast({
							title: "支付失败，请重新尝试",
							icon: 'error'
						});
					},
					"complete": function(res) {}
				})

			}
		}
	}
	// import login from "./login.js";
	// export default login;
</script>

<style>
	@import url("./login.css");
</style>